import {ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, TemplateRef, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup} from "@angular/forms";
import {NzTableQueryParams} from "ng-zorro-antd/table";
import {finalize} from "rxjs/operators";
import {ActivatedRoute, Router} from "@angular/router";
import {NzMessageService} from "ng-zorro-antd/message";
import {NzModalService} from "ng-zorro-antd/modal";
import {AdminService} from "../../core/services/store/admin.service";
import {MyTableConfig} from "../../shared/components/ant-table/ant-table.component";
import {PageHeaderType} from "../../shared/components/page-header/page-header.component";
import {SearchCommonVO} from "../../core/services/types";
import {WindowService} from "../../core/services/common/window.service";
import {AdminKey} from "../../config/constant";
import {IdentifyIdService} from "../../core/services/store/biz-store-service/identify-id/identify-id.service";
import {
  BasicInformationList,
  BasicInformationService
} from "../../core/services/http/classification-identification/basic-information.service";
import {ModalBtnStatus} from "../../widget/base-modal";
import FileSaver from "file-saver";
import {MsdsModalsService} from "../../widget/biz-widget/msds-modal/msds-modals.service";

interface SearchParam {
  dangerNo: string;
  cnName: string;
  cas: string;
  alias: string;
}

@Component({
  selector: 'app-classification-identification',
  templateUrl: './classification-identification.component.html',
  styleUrls: ['./classification-identification.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ClassificationIdentificationComponent implements OnInit {
  @ViewChild('operationTpl', {static: true}) operationTpl!: TemplateRef<any>;
  searchParam: Partial<SearchParam> = {};
  validateForm!: FormGroup;
  isCollapse = true;
  tableConfig!: MyTableConfig;
  pageHeaderInfo: Partial<PageHeaderType> = {
    title: '列表展示',
    breadcrumb: ['首页', '化学品分辨类别', '化学品名称展示']
  };
  dataList: BasicInformationList[] = [];
  checkedCashArray: BasicInformationList[] = [];

  constructor(private fb: FormBuilder, private router: Router,
              private identifyIdService: IdentifyIdService, private message: NzMessageService,
              private cdr: ChangeDetectorRef, private dataService: BasicInformationService,
              private modalSrv: NzModalService, private windowSrv: WindowService, private modalService: MsdsModalsService,
              public AdminService: AdminService, private activatedRoute: ActivatedRoute) {
  }

  reloadTable(): void {
    this.message.info('刷新成功');
    this.tableConfig.pageIndex = 1;
    this.getDataList();
  }

  // 最左侧复选框选中触发
  selectedChecked(e: any): void {
    this.checkedCashArray = [...e];
  }

  search(): void {
    this.tableConfig.pageIndex = 1;
    this.getDataList();
  }

  // 触发表格变更检测
  tableChangeDectction(): void {
    // 改变引用触发变更检测。
    this.dataList = [...this.dataList];
    this.cdr.detectChanges();
  }

  tableLoading(isLoading: boolean): void {
    this.tableConfig.loading = isLoading;
    this.tableChangeDectction();
  }

  // 修改一页几条
  changePageSize(e: number): void {
    this.tableConfig.pageSize = e;
  }

  getDataList(e?: NzTableQueryParams): void {
    this.tableLoading(true);
    const params: SearchCommonVO<any> = {
      pageSize: this.tableConfig.pageSize!,
      pageNum: e?.pageIndex! || this.tableConfig.pageIndex!,
      filters: this.searchParam
    };
    this.dataService.getBasicInformationList(params).pipe(finalize(() => this.tableLoading(false))).subscribe((data) => {
      const {list, total, pageNum} = data;
      this.dataList = [...list];
      this.tableConfig.total = total!;
      this.tableConfig.pageIndex = pageNum!;
      this.tableLoading(false);
      this.checkedCashArray = [...this.checkedCashArray];
    });
  }

  /*重置*/
  resetForm(): void {
    this.searchParam = {};
    this.tableConfig.pageIndex = 1;
    this.getDataList();
  }

  /*新增*/
  add(): void {
    this.identifyIdService.setIdentifyIdStore(-1);
    this.router.navigate(['default/classification-identification/add-edit-identify']);
  }

  // 修改
  edit(id: number): void {
    this.identifyIdService.setIdentifyIdStore(id);
    this.router.navigate(['/default/classification-identification/add-edit-identify']);
  }

  /*删除*/
  del(id: number[]): void {
    this.modalSrv.confirm({
      nzTitle: '确定要删除吗？',
      nzContent: '删除后不可恢复',
      nzOnOk: () => {
        this.tableLoading(true);
        this.dataService.delBasicInformation(id).pipe(finalize(() => {
          this.tableLoading(false);
        })).subscribe(() => {
          if (this.dataList.length === 1) {
            this.tableConfig.pageIndex--;
          }
          this.getDataList();
          // @ts-ignore
          this.checkedCashArray.splice(this.checkedCashArray.findIndex(item => item.id === id), 1);
        }, error => this.tableLoading(false));
      }
    });
  }

  export(): void {
    if (this.checkedCashArray.length > 0) {
      const tempArrays: number[] = [];
      this.checkedCashArray.forEach((item) => {
        tempArrays.push(item.id);
      });
      /*获取选中项的数据列表*/
      this.dataService.getCheckList(tempArrays).subscribe(item => {
        this.modalService.show({
          nzTitle: '物质辨识列表',
          nzWidth: '800px',
        }, {arrays: item}).subscribe((data) => {
          if (!data || data.status === ModalBtnStatus.Cancel) {
            return;
          }
          this.dataService.getIdentifyExport(data.modalValue).subscribe(tempRes => {
            const blob = new Blob([tempRes], {type: 'text/plain;charset=utf-8'});
            FileSaver.saveAs(blob, '物质辨识表.doc');
          });
          this.checkedCashArray = [];
          this.cdr.detectChanges();
        });
      })
    } else {
      this.message.error('请勾选数据');
      return;
    }
  }

  _onReuseInit(): void {
    this.getDataList();
  }

  ngOnInit(): void {
    this.initTable();
    this.activatedRoute.queryParams.subscribe(res => {
      if (typeof (res['userId']) != undefined) {
        if (res['userId'] === '1') {
          this.AdminService.isAdmin = true;
          this.windowSrv.setSessionStorage(AdminKey, res['userId']);
        }
      }
    });
  }

  private initTable(): void {
    this.tableConfig = {
      needNoScroll: true,
      showCheckbox: true,
      headers: [
        {
          title: '危序号',
          width: 200,
          field: 'dangerNo',
        },
        {
          title: '品名',
          width: 350,
          field: 'cnName',
        },
        {
          title: '别名',
          width: 350,
          field: 'alias',
        },
        {
          title: '重大危险源物质',
          width: 250,
          field: 'dangerMatterKey',
        },
        {
          title: 'CAS号',
          width: 200,
          field: 'cas',
        },
        {
          title: '操作',
          tdTemplate: this.operationTpl,
          fixed: true,
          fixedDir: "right"
        }
      ],
      total: 0,
      loading: true,
      pageSize: 10,
      pageIndex: 1,
    };
  }

}
